import {RouteRecordRaw,createRouter,createWebHashHistory,createWebHistory} from 'vue-router'
//定义路由规则对象集合
import api from '@/api'
import {message} from 'ant-design-vue'
import useTabStore from '@/store/tabs'
// import useUserStore from '@/store/users'
const routes:Array<RouteRecordRaw>=[
    {
        path:'/login',
        name:'login',
        component:()=>import('@/views/Login.vue')
    },
    {
      path:'/',
      redirect:'/home'
    },
    {
        path:'/home',
        component:()=>import('@/views/Home.vue'),
    }
]
//定义router对象
const router=createRouter({
    routes:routes,
    //history:createWebHashHistory() //hash模式，
    history:createWebHistory() //history模式
})
/**
 * 路由守卫
 */
router.beforeEach(async(to,from,next)=>{
    //执行useTabStore方法
   const store=useTabStore()
   if(to.path=="/login"){
     next()
   }else{
     //没有登录直接进入
     //获取token
     let token=localStorage.getItem('token')
     console.log('token是否',token);
     //如果没有token
     if(!token){
        //跳转到登录页面上去
        next("/login")
     }else{
       try {
          await api.users.getUserInfo()
          store.addTabs(to.meta)
          next()
         
       } catch (error) {
           message.error('token已经失效，请重新登录')
           next('/login')
       }
     }
   }
})
export default router




